--================================================
--  Create Inline Table-valued Function template
--================================================
USE TIENGUITIETKIEM
GO
--ham sinh ma tu dong
IF OBJECT_ID (N'dbo.FN_NextID') IS NOT NULL
   DROP FUNCTION dbo.FN_NextID
GO

CREATE FUNCTION dbo.FN_NextID (@LastId varchar(10),@Prefix varchar(10),@Size int)
	RETURNS varchar(10)
AS
    BEGIN
        IF(@Lastid = '')
            set @Lastid = @Prefix + REPLICATE (0,@Size - LEN(@Prefix)) 
        declare @Num_NextId int
		declare @Nextid varchar(10)
        set @LastId = LTRIM(RTRIM(@LastId))
        set @Num_NextId = REPLACE(@LastId,LEFT(@LastId, LEN(@Prefix)),'') + 1
        set @Size = @Size - LEN(@Prefix)
        set @Nextid = @Prefix + REPLICATE (0,@Size - LEN(@Prefix)) 
        set @Nextid = @Prefix + RIGHT(REPLICATE(0, @size) + CONVERT (VARCHAR(MAX), @Num_NextId), @Size)
        return @Nextid
    END;
GO
